package jp.tkym.labs.util.csv;

import java.util.ArrayList;
import java.util.List;

class CsvLineBuffer{
	private static final String COMMA_SEPARATOR = ",";
	private final String quoteStr;
	
	private StringBuilder stringBuilder = new StringBuilder();
	private List<String> rowData = new ArrayList<String>();
	private boolean inBetweenQuote = false;
	
	CsvLineBuffer(){
		this('"');
	}
	
	CsvLineBuffer(char quoteChar){
		quoteStr = Character.toString(quoteChar);
	}
	
	void addLine(String line){
		for(String separetedStr : line.split(COMMA_SEPARATOR)){
			verifyQuote(separetedStr);
			buildString(separetedStr);
		}
	}
	
	void buildString(String separatedStr){
		stringBuilder.append(separatedStr);
		if(!inBetweenQuote){
			String str = stringBuilder.toString();
			str = removeQuote(str);
			rowData.add(str);
			stringBuilder = new StringBuilder();
		}
	}
	
	void verifyQuote(String separatedStr){
		boolean startWithQuote = separatedStr.startsWith(quoteStr);
		boolean endWithQuote = separatedStr.endsWith(quoteStr);
		if(!inBetweenQuote && startWithQuote && endWithQuote) return;
		
		if(inBetweenQuote){
			if(endWithQuote)inBetweenQuote = false;
		}else{
			if(startWithQuote)inBetweenQuote = true;
		}
	}
	
	String removeQuote(String separatedStr){
		String s1 = separatedStr;
		if(s1.startsWith(quoteStr)){
			s1 = s1.substring(1);
		}
		if(s1.endsWith(quoteStr)){
			int length = s1.length();
			s1 = s1.substring(0, length - 1); 
		}
		return s1;
	}
	
	String[] readRow(){
		if(inBetweenQuote)throw new IllegalStateException("not completed!! csv file reading...");
		String[] retArray = new String[rowData.size()];
		rowData.toArray(retArray);
		rowData.clear();
		return retArray;
	}
	
	boolean isCompleted(){
		return !inBetweenQuote;
	}
}